import 'package:flutter/material.dart';
import 'package:flutter_soundmagus/page/cross/cross_controller.dart';
import 'package:flutter_soundmagus/model/model.dart';
import 'package:flutter_soundmagus/page/eq/eq_controller.dart';
import 'package:flutter_soundmagus/page/inout/summing_controller.dart';
import 'package:flutter_soundmagus/util/util.dart';
import 'package:flutter_soundmagus/widget/eq/DrawFunction.dart';
import 'package:flutter_soundmagus/widget/eq/EqView.dart';
import 'package:flutter_soundmagus/widget/eq/eq_wdiget.dart';
import 'package:flutter_soundmagus/widget/menu_bottom_bar.dart';
import 'package:flutter_soundmagus/widget/widget.dart';
import 'package:get/get.dart';
import '../inout/widget/output_graph.dart';
part 'cross_view_part.dart';

class CrossView extends StatefulWidget {
  const CrossView({super.key});

  @override
  State<CrossView> createState() => _CrossViewState();
}

class _CrossViewState extends State<CrossView> with MsgParserRefreshMixin {
  final c = Get.find<CrossController>();
  final eqController = Get.find<EqController>();
  final EqWidgetController eqWidgetController = EqWidgetController(0);
  EqView get eqView => eqWidgetController.eqView;
  @override
  void initState() {
    super.initState();

    c.passControllers.forEach((element) {
      element.update();
    });

    everAll([
      c.passControllers.first.freq,
      c.passControllers.first.slope,
      c.passControllers.first.xielv,
      c.passControllers.first.passType,
      c.passControllers.last.freq,
      c.passControllers.last.slope,
      c.passControllers.last.xielv,
      c.passControllers.last.passType,
      c.selectCh,
      eqController.db,
      eqController.freq,
      eqController.q
    ], (v) {
      updateEq(context);
    });

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      updateEq(context);
    });

    Future.delayed(Duration(seconds: 1), () => updateEq(context));

    observeRefresh();
  }

  @override
  void refreshState(bool needSendData) {
    super.refreshState(needSendData);
    if (mounted) {
      updateEq(context);
    }
  }

  Widget _buildEq(BuildContext context) {
    return EqWidget(
      controller: eqWidgetController,
      pdCount: 0,
    );
  }

  void updateEq(BuildContext context, {EQModel? srcEqModel}) {
    var selectCH = c.model.selectCH, eqmodel = srcEqModel ?? DataMng().eqModel;
    var items = eqmodel.getItemsModel(selectCH),
        q = items.map((e) => e.q.toDouble()).toList(),
        eq = items.map((e) => e.ch.toDouble()).toList(),
        freq = items.map((e) => e.freq.toDouble()).toList();
    //EQ曲线
    eqView.setPEQ(q, eq, freq,
        width: MediaQuery.of(context).size.width.toInt());

    //xover
    if (c.model.chConfig.isChGrouped(ch: selectCH)) {
      eqView.setColor(0);
    } else {
      eqView.setColor(selectCH);
    }

    var xoverModel = c.model, cModel = xoverModel.itemModel();
    //high slope、low slope
    var high = DrawFunction.getOctType(cModel, true),
        low = DrawFunction.getOctType(cModel, false);
    eqView.setXover([cModel.low.freq.toDouble(), cModel.high.freq.toDouble()],
        [low.toDouble(), high.toDouble()]);

    // eqView.reArray();
    // eqView.refreshPEQ1(0);
    eqView.reXover();
    // eqView.refreshXover2(0);
    eqWidgetController.update(); //强制刷新才能更新eq曲线，这里曲线绘制应该有点问题
  }

  SummingController get sc => Get.find<SummingController>();

  @override
  Widget build(BuildContext context) {
    print('build crossview');

    return Column(
      children: [
        Container(
          padding: EdgeInsets.only(top: 20.w, left: 60.w, right: 60.w),
          height: 90,
          child: _buildEq(context), //曲线图
        ),
        Expanded(
          child: Stack(children: [
            Padding(
              padding: EdgeInsets.only(
                  left: Get.mediaQuery.viewPadding.left, right: 40),
              child: Row(
                // mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Flexible(
                    child: CrossPassView(
                      c.passControllers.first,
                      highPass: true,
                    ),
                    flex: 1,
                  ),
                  Flexible(
                    child: Container(),
                    flex: 2,
                  ),
                  Flexible(
                    child: CrossPassView(c.passControllers.last),
                    flex: 1,
                  ),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 40),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Flexible(
                    child: Container(),
                    flex: 1,
                  ),
                  Flexible(
                      flex: 2,
                      child: Obx(() => OutputGraph(
                            mini: true && sc.v.value >= 0,
                            leftDrive: sc.leftDrive.value,
                            mode: sc.outputModeLast.value,
                            miniScale: 0.65,
                            selecteds: c.chSelects.map((e) => e.value).toList(),
                            onChanged: (v) {
                              c.setChSelected(ch: v);
                            },
                          ))),
                  Flexible(
                    child: Container(),
                    flex: 1,
                  ),
                ],
              ),
            ),
          ]),
        ),
        SizedBox(
          height: 10,
        ),
        MenuBottomBar(
          title: 'Crossover',
          left: List.generate(
            2,
            (index) => SizedBox(
                width: (Get.width - 202.w) / 4,
                height: 30,
                child: Obx(() => GroupLinkButton(
                      onPressed: () => c.setGroup(groupIndex: index),
                      onLongPress: () => c.cancelGroup(groupIndex: index),
                      linked: c.groupSelects[index].value,
                      title1: DataMng.shared.chNames[index * 2].value,
                      title2: DataMng.shared.chNames[index * 2 + 1].value,
                    ))),
          ),
          right: List.generate(
            2,
            (i) {
              var index = i + 2;
              return SizedBox(
                  width: (Get.width - 202.w) / 4,
                  height: 30,
                  child: Obx(() => GroupLinkButton(
                        onPressed: () => c.setGroup(groupIndex: index),
                        onLongPress: () => c.cancelGroup(groupIndex: index),
                        linked: c.groupSelects[index].value,
                        title1: DataMng.shared.chNames[index * 2].value,
                        title2: DataMng.shared.chNames[index * 2 + 1].value,
                      )));
            },
          ),
        ),
      ],
    );
  }
}
